// echarts-components.js
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'

/**
 * ECharts 组件封装
 * 包含多种常用图表类型，可直接在Vue组件中引入使用
 */

// 主题颜色配置
const themeColors = {
  primary: '#4ADE80',
  secondary: '#115D2E',
  background: 'rgba(17, 93, 46, 0.2)'
}

/**
 * 基础折线图
 * @param {HTMLElement} dom - 图表容器DOM元素
 * @param {Array} xData - x轴数据
 * @param {Array} yData - y轴数据
 * @param {Object} options - 自定义配置选项
 */
const initLineChart = (dom, xData, yData, options = {}) => {
  const chart = echarts.init(dom)

  const defaultOptions = {
    xAxis: {
      type: 'category',
      data: xData,
      axisLine: {
        lineStyle: {
          color: themeColors.primary
        }
      },
      axisLabel: {
        color: '#fff'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: themeColors.primary
        }
      },
      axisLabel: {
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)'
        }
      }
    },
    series: [{
      data: yData,
      type: 'line',
      smooth: true,
      lineStyle: {
        color: themeColors.primary,
        width: 3
      },
      itemStyle: {
        color: themeColors.primary
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(74, 222, 128, 0.5)'
          },
          {
            offset: 1,
            color: 'rgba(74, 222, 128, 0.1)'
          }
        ])
      }
    }],
    grid: {
      left: '3%',
      right: '3%',
      bottom: '3%',
      top: '5%',
      containLabel: true
    },
    backgroundColor: themeColors.background,
    ...options
  }

  chart.setOption(defaultOptions)
  return chart
}

/**
 * 柱状图
 * @param {HTMLElement} dom - 图表容器DOM元素
 * @param {Array} xData - x轴数据
 * @param {Array} yData - y轴数据
 * @param {Object} options - 自定义配置选项
 */
const initBarChart = (dom, xData, yData, options = {}) => {
  const chart = echarts.init(dom)

  const defaultOptions = {
    xAxis: {
      type: 'category',
      data: xData,
      axisLine: {
        lineStyle: {
          color: themeColors.primary
        }
      },
      axisLabel: {
        color: '#fff',
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: themeColors.primary
        }
      },
      axisLabel: {
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)'
        }
      }
    },
    series: [{
      data: yData,
      type: 'bar',
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(74, 222, 128, 0.5)' },
          { offset: 0.5, color: 'rgba(74, 222, 128, 0.1)' },
          { offset: 1, color: 'rgba(74, 222, 128, 0.1)' }
        ])
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(74, 222, 128, 0.5)'
          },
          {
            offset: 1,
            color: 'rgba(74, 222, 128, 0.1)'
          }
        ])
      }
    }],
    grid: {
      left: '3%',
      right: '3%',
      bottom: '10%',
      top: '5%',
      containLabel: true
    },
    backgroundColor: themeColors.background,
    ...options
  }

  chart.setOption(defaultOptions)
  return chart
}

/**
 * 饼图
 * @param {HTMLElement} dom - 图表容器DOM元素
 * @param {Array} data - 饼图数据 [{value: 335, name: '直接访问'}, ...]
 * @param {Object} options - 自定义配置选项
 */
const initPieChart = (dom, data, options = {}) => {
  const chart = echarts.init(dom)

  const defaultOptions = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        color: '#fff'
      }
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: themeColors.secondary,
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center',
          color: '#fff'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ],
    backgroundColor: themeColors.background,
    ...options
  }

  chart.setOption(defaultOptions)
  return chart
}

/**
 * Vue 组合式API封装
 * @param {String} chartType - 图表类型 ('line', 'bar', 'pie')
 * @param {Array} chartData - 图表数据
 * @param {Object} options - ECharts配置选项
 */
export const useEChart = (chartType, chartData, options = {}) => {
  const chartDom = ref(null)
  let chartInstance = null

  // 初始化图表
  const initChart = () => {
    if (!chartDom.value) return

    switch (chartType) {
      case 'line':
        chartInstance = initLineChart(
          chartDom.value,
          chartData.xData || [],
          chartData.yData || [],
          options
        )
        break
      case 'bar':
        chartInstance = initBarChart(
          chartDom.value,
          chartData.xData || [],
          chartData.yData || [],
          options
        )
        break
      case 'pie':
        chartInstance = initPieChart(
          chartDom.value,
          chartData || [],
          options
        )
        break
      default:
        console.warn(`Unknown chart type: ${chartType}`)
    }
  }

  // 更新图表数据
  const updateChart = (newData) => {
    if (!chartInstance) return

    const updateOptions = {
      series: [{
        data: newData.yData || newData
      }]
    }

    if (newData.xData) {
      updateOptions.xAxis = { data: newData.xData }
    }

    chartInstance.setOption(updateOptions)
  }

  // 响应式调整大小
  const resizeHandler = () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  }

  onMounted(() => {
    initChart()
    window.addEventListener('resize', resizeHandler)
  })

  onBeforeUnmount(() => {
    if (chartInstance) {
      window.removeEventListener('resize', resizeHandler)
      chartInstance.dispose()
    }
  })

  return {
    chartDom,
    updateChart
  }
}

/**
 * 大数据量柱图
 */
const initBigBarChart = (dom, data, options = {}) => {
  function getVirtualData(year) {
    const date = +echarts.time.parse(year + '-01-01');
    const end = +echarts.time.parse(year + '-12-31');
    const dayTime = 3600 * 24 * 1000;
    const data = [];
    for (let time = date; time <= end; time += dayTime) {
      data.push([
        echarts.time.format(time, '{yyyy}-{MM}-{dd}', false),
        Math.floor(Math.random() * 10000)
      ]);
    }
    return data;
  }
  option = {
    visualMap: {
      show: false,
      min: 0,
      max: 10000
    },
    calendar: {
      range: '2017'
    },
    series: {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data: getVirtualData('2017')
    }
  };
  const chart = echarts.init(dom);
  chart.setOption(option);
  return chart;
}
/**
 * 默认导出所有图表初始化方法
 * 可以在不使用Vue组合式API的情况下直接调用
 */
export default {
  initLineChart,
  initBarChart,
  initPieChart,
  initBigBarChart
}